#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "Calculator.hpp"
#include "Socket.hpp"

const std::string operation = "+-*/%";

void UsePage(char *argv[])
{
    std::cout << std::endl
              << argv[0] << " [ip]  [port]" << std::endl;
}

std::string Package_Request(int x, int y, char op)
{
    Request rq(x, y, op);

    std::string request_str = rq.serialize();
    std::string package = Encode(request_str);

    return package;
}

void Get_Result(std::string &ret_str, int sockfd, int *presult, int *pcode)
{
    char inbuffer[1024];
    int n = read(sockfd, inbuffer, sizeof(inbuffer));
    if (n > 0)
    {
        inbuffer[n] = 0;
        ret_str += inbuffer;
        std::string content = Decode(ret_str);
        if (content.empty())
            return;

        Respond rp;
        rp.deserialize(content);
        *presult = rp.Get_result();
        *pcode = rp.Get_code();
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        UsePage(argv);
        exit(1);
    }
    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];

    // 创建套接字
    Socket sock;
    sock.Init();
    int sockfd = sock.Getsockfd();

    sock.Connect(ip, port);

    ssize_t len = operation.size();
    std::string get_ret;
    for (;;)
    {
        int a = rand() % 100 + 1, b = rand() % 100;
        char op = operation[rand() % len];

        std::string package = Package_Request(a, b, op);
        std::cout << "send a package " << package << std::endl;

        write(sockfd, package.c_str(), package.size());

        int result , code = -1;
        Get_Result(get_ret, sockfd, &result, &code);
        if (code >= 0)
        {
            std::cout << "result is " << result << " , code  is  " << code << std::endl;
            std::cout << "--------------------------" << std::endl;
        }

        sleep(1);
    }

    return 0;
}